package com.mew.auc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mew.auc.annotation.AseEncrypt;
import com.mew.auc.provide.SasFeignService;
import com.mew.auc.rest.IOSBuyRequestMessage;
import com.mew.auc.rest.TestBuyRequestMessage;
import com.mew.auc.util.GooglePlayUtils;
import com.mew.auc.util.IOSPlayUtils;
import com.mew.common.dc.db.GoldBuyService;
import com.mew.common.dc.db.LevelConfigService;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.db.UserService;
import com.mew.common.dc.mapper.RechargeRecordMapper;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.entity.config.MoneyProduct;
import com.mew.common.entity.record.RechargeRecord;
import com.mew.common.entity.user.Profile;
import com.mew.common.entity.user.User;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.sas.EFTSasRequest;
import com.mew.common.rest.user.BuyRequestMessage;
import com.mew.common.rest.user.UserMoneyResponseMessage;
import com.mew.common.util.StringUtils;
import com.mew.common.vo.vip.VipUp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/buy")
public class GoldBuyController {
    @Autowired
    private SasFeignService sasFeignService;

    @Autowired
    private ProfileService profileService;
    @Autowired
    private LevelConfigService levelConfigService;
    @Autowired
    private GoldBuyService goldBuyService;
    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;
    @Autowired
    private GooglePlayUtils googlePlayUtils;

    /**
     * 钱买钻石
     *
     * @return
     */
    @PostMapping("/jewelNumber")
    @ResponseBody
    @AseEncrypt
    public String jewelNumber(@RequestBody String param) {
        BuyRequestMessage req = JSON.parseObject(param, BuyRequestMessage.class);
        Long uid = req.getUid();
        String packageName = req.getPackageName();
        String productId = req.getProductId();
        String purchaseToken = req.getPurchaseToken();

        VipUp vipUp = new VipUp();
        vipUp.setMessage(1405 + "");
        if (null == req || null == uid || StringUtils.isEmpty(packageName) || StringUtils.isEmpty(productId) || StringUtils.isEmpty(purchaseToken)) {
            vipUp.setStatus(ResponseCode.ParamInvalid.code());
            log.info("/buy/jewelNumber 请求参数无效 uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);
            return JSON.toJSONString(vipUp);
        }

        Profile profile = profileService.getRedisProfileById(uid);

        if (null == profile) {
            vipUp.setStatus(ResponseCode.UserNotExist.code());
            log.info("/buy/jewelNumber 无该用户 uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);
            return JSON.toJSONString(vipUp);
        }

        log.info("/buy/jewelNumber uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);

        //todo 验证订单

        RechargeRecord record = googlePlayUtils.getGoogleProductResponse(req);

        if (null == record || StringUtils.isEmpty(record.getOrderId())) {
            vipUp.setStatus(ResponseCode.NoProduct.code());
            log.info("/buy/jewelNumber 订单无效 uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);
            return JSON.toJSONString(vipUp);
        }

        RechargeRecord rechargeRecord = rechargeRecordMapper.selectById(record.getOrderId());

        log.info("rechargeRecord:{}", rechargeRecord);

        if (null != rechargeRecord && StringUtils.isNotEmpty(rechargeRecord.getOrderId())) {
            vipUp.setStatus(ResponseCode.HaveProduct.code());
            log.info("/buy/jewelNumber 订单已存在 uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);
            return JSON.toJSONString(vipUp);
        }

        try {
            record.setUserId(uid);
            record.setType((byte) 1);
            int insert = rechargeRecordMapper.insert(record);
        } catch (Exception e) {
            log.info("/buy/jewelNumber 充值记录添加失败 uid:{} ,e:{}", uid, e);
            vipUp.setStatus(ResponseCode.HaveProduct.code());
            return JSON.toJSONString(vipUp);
        }

        //if (insert==1){}

        MoneyProduct moneyProduct = goldBuyService.getMoneyProduct(req.getProductId());

        if (null == moneyProduct) {
            log.info("/buy/jewelNumber 无该商品 uid:{} packageName:{} productId:{} purchaseToken:{}", uid, packageName, productId, purchaseToken);
            vipUp.setStatus(ResponseCode.NoProduct.code());
            return JSON.toJSONString(vipUp);
        }

        long m = moneyProduct.getMoney();
        long j = moneyProduct.getJewel();

        vipUp = levelConfigService.vipLevelUp(uid, m, j);

        sasPay(uid,m,vipUp);

        profile = profileService.getRedisProfileById(uid);
        vipUp.byProfile(profile);
        vipUp.setMessage(1405 + "");
        String jsonString = JSON.toJSONString(vipUp);
        log.info("充值成功：uid{} {}", uid, jsonString);
        //TODO 买钻石-----
        return jsonString;
    }

    /**
     * IOS钱买钻石
     *
     * @return
     */
    @PostMapping("/jewelNumber_IOS")
    @ResponseBody
    @AseEncrypt
    public String jewelNumberIOS(@RequestBody String param) {
        log.info("客户端传过来的值:{}" + param);
        VipUp vipUp = new VipUp();
        vipUp.setMessage(1405 + "");

        IOSBuyRequestMessage req = JSON.parseObject(param, IOSBuyRequestMessage.class);
        Long uid = req.getUid();
        String json = req.getJson();
        if (null == uid || null == json || StringUtils.isEmpty(json)) {
            vipUp.setStatus(ResponseCode.ParamInvalid.code());
            log.info("/buy/jewelNumber 请求参数无效 uid:{} param:{}", uid, json);
            return JSON.toJSONString(vipUp);
        }
        String verifyResult = IOSPlayUtils.buyAppVerify(json, 1);            //1.先线上测试    发送平台验证
        if (verifyResult == null) {                                            // 苹果服务器没有返回验证结果
            vipUp.setStatus(ResponseCode.NoProduct.code());
            log.info("/buy/jewelNumber 订单无效 uid:{} param:{}", uid, json);
            return JSON.toJSONString(vipUp);
        } else {                                                                // 苹果验证有返回结果
            log.info("线上，苹果平台返回JSON:" + verifyResult);
            JSONObject job = JSONObject.parseObject(verifyResult);
            String states = job.getString("status");
            //0 正常
            //21000 App Store不能读取你提供的JSON对象
            //21002 receipt-data域的数据有问题
            //21003 receipt无法通过验证
            //21004 提供的shared secret不匹配你账号中的shared secret
            //21005 receipt服务器当前不可用
            //21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
            //21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
            //21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
            if ("21007".equals(states)) {                                            //是沙盒环境，应沙盒测试，否则执行下面
                verifyResult = IOSPlayUtils.buyAppVerify(json, 0);            //2.再沙盒测试  发送平台验证
                log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
                job = JSONObject.parseObject(verifyResult);
                states = job.getString("status");
            }
            log.info("苹果平台返回值：job" + job);
            if (states.equals("0")) { // 前端所提供的收据是有效的    验证成功
 /*               String r_receipt = job.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(r_receipt);
                String in_app = returnJson.getString("in_app");
                JSONObject in_appJson = JSONObject.parseObject(in_app.substring(1, in_app.length() - 1));
                //具体信息
                String transaction_id = in_appJson.getString("transaction_id");   // 订单号
                String product_id = in_appJson.getString("product_id");//商品ID*/

                String r_receipt = job.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(r_receipt);
                if(!StringUtils.isEmpty(returnJson.getString("in_app"))){
                    String in_app = returnJson.getString("in_app");
                    returnJson = JSONObject.parseObject(in_app.substring(1, in_app.length() - 1));
                }
                //具体信息
                String transaction_id = returnJson.getString("transaction_id");   // 订单号
                String product_id = returnJson.getString("product_id");//商品ID



/************************************************+自己的业务逻辑开始+**********************************************************/
                RechargeRecord rechargeRecord = rechargeRecordMapper.selectById(transaction_id);
                if (null != rechargeRecord && StringUtils.isNotEmpty(rechargeRecord.getOrderId())) {
                    vipUp.setStatus(ResponseCode.HaveProduct.code());
                    log.info("/buy/jewelNumber 订单已存在 uid:{} verifyResult:{} ", uid, verifyResult);
                    return JSON.toJSONString(vipUp);
                }
                RechargeRecord record = new RechargeRecord();
                record.setOrderId(transaction_id);
                record.setDeveloperPayload(verifyResult);
               record.setKind(json);
                record.setUserId(uid);
                record.setType((byte) 2);
                rechargeRecordMapper.insert(record);
                //if (insert==1){}
                MoneyProduct moneyProduct = goldBuyService.getMoneyProduct(product_id);

                if (null == moneyProduct) {
                    log.info("/buy/jewelNumber 无该商品 uid:{} verifyResult:{} ", uid, verifyResult);
                    vipUp.setStatus(ResponseCode.NoProduct.code());
                    return JSON.toJSONString(vipUp);
                }

                long m = moneyProduct.getMoney();
                long j = moneyProduct.getJewel();

                vipUp = levelConfigService.vipLevelUp(uid, m, j);

                sasPay(uid,m,vipUp);

                Profile profile = profileService.getRedisProfileById(uid);
                vipUp.byProfile(profile);
                vipUp.setMessage(1405 + "");
                String jsonString = JSON.toJSONString(vipUp);
                log.info("充值成功：uid{} {}", uid, jsonString);
            } else {
                vipUp.setStatus(ResponseCode.SysException.code());
                vipUp.setMessage(1405+":"+states);
            }
        }
        return JSON.toJSONString(vipUp);
    }

    /**
     * 购买钻石  测试
     *
     * @return
     */
    @GetMapping("/jewelNumber_TEST/{uid}/{product_id}")
    @ResponseBody
/*    @AseEncrypt*/
    public String jewelNumberTEST(@PathVariable("uid") Long uid,@PathVariable("product_id")String product_id) {
        log.info("客户端传过来的值:" + uid + "," +product_id);
        VipUp vipUp = new VipUp();
        vipUp.setMessage(1405 + "");

        RechargeRecord record = new RechargeRecord();
        record.setOrderId("TEST-"+ UUID.randomUUID());
        record.setUserId(uid);
        record.setType((byte) 3);
        rechargeRecordMapper.insert(record);
        MoneyProduct moneyProduct = goldBuyService.getMoneyProduct(product_id);

        if (null == moneyProduct) {
            log.info("/buy/jewelNumber 无该商品 uid:{} product_id:{} ", uid, product_id);
            vipUp.setStatus(ResponseCode.NoProduct.code());
            return JSON.toJSONString(vipUp);
        }

        long m = moneyProduct.getMoney();
        long j = moneyProduct.getJewel();

        vipUp = levelConfigService.vipLevelUp(uid, m, j);

        sasPay(uid,m,vipUp);

        Profile profile = profileService.getRedisProfileById(uid);
        vipUp.byProfile(profile);
        vipUp.setMessage(1405 + "");
        String jsonString = JSON.toJSONString(vipUp);
        log.info("充值成功：uid{} {}", uid, jsonString);
        return JSON.toJSONString(vipUp);
    }


    /**
     * 钱买钻石
     * @return
     */
    @RequestMapping("/res")
    @ResponseBody
    public void res(String code,String scope){
        log.info(code);
        log.info(scope);

    }

    /**
     * 充值埋點
     * @param uid
     * @param m
     * @param vipUp
     */
    private void sasPay(long uid,long m,VipUp vipUp){
        EFTSasRequest build = EFTSasRequest.builder()
                .eftType(GoldProcessType.Jewe.code())
                .userId(uid)
                .number(m)
                .isLevelUp(vipUp.isLevelUp())
                .Level(vipUp.getLevel())
                .build();
        sasFeignService.eftPay(build);
    }
}
